// 基于 element-ui 的 Loading 封装，element-ui 的 Loading.service() 返回的都是同一个 Loading 实例，且其中任何一个调用 close 方法都会导致 Loading 直接关闭
// 通过 show、close 和 counter 来管理这个单一 loading 实例
import { Loading } from "element-ui";

let loadingInstance = null;
let loadEndCallBack = [];

function initLoading(
  option = {
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.8)"
  }
) {
  loadingInstance = Loading.service(option);
  loadingInstance._count = 0;
}

function show() {
  if (!loadingInstance || loadingInstance._count <= 0) {
    initLoading();
  }
  loadingInstance._count++;
}

function close() {
  if (!loadingInstance) return;
  loadingInstance._count--;
  if (loadingInstance._count <= 0) {
    loadingInstance.close();
    loadingInstance._count = 0;
    executeLoadEndCallBack();
  }
}

function closeAll() {
  if (!loadingInstance) return;
  loadingInstance.close();
  loadingInstance._count = 0;
  executeLoadEndCallBack();
}

function onLoadEnd(callBack) {
  if (loadingInstance._count <= 0) {
    typeof callBack === "function" && callBack();
  } else {
    loadEndCallBack.push(callBack);
  }
}

function executeLoadEndCallBack() {
  loadEndCallBack.forEach((callBack) => {
    typeof callBack === "function" && callBack();
  });
  loadEndCallBack = [];
}

export default { show, close, closeAll, onLoadEnd };
